package fina2.dcs.mail.dbo.bean;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.LocalBinding;

import fina2.dcs.mail.dbo.domain.MailReply;

@Stateless
@LocalBinding(jndiBinding = "MailReplyBean/local")
@TransactionManagement(TransactionManagementType.BEAN)
public class MailReplyBean implements MailReplyLocal {

	@PersistenceContext(name = "mailDBO")
	private EntityManager manager;

	@Resource
	private UserTransaction ut;

	private Logger log = Logger.getLogger(getClass());

	@Override
	public void saveMailReply(MailReply mailReply) {
		try {
			if (mailReply != null) {
				ut.begin();
				manager.persist(mailReply);
				ut.commit();
				log.info("Save: Mail Replay");
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	@Override
	public void updateMailStatus(long messageId, int status) {
		try {
			ut.begin();
			MailReply mailReply = manager.find(MailReply.class, messageId);
			mailReply.setSendStatus(status);
			ut.commit();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MailReply> loadMails(int sendStatus) {
		List<MailReply> result = null;
		try {
			ut.begin();
			Query query = manager.createQuery("SELECT m FROM " + MailReply.class.getSimpleName() + " AS m WHERE  m.sendStatus=?");
			query.setParameter(1, sendStatus);
			result = query.getResultList();
			ut.commit();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return result;
	}
}
